import org.flowable.engine.*;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.impl.cfg.StandaloneProcessEngineConfiguration;
import org.flowable.engine.repository.Deployment;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;

import java.util.*;

public class HolidayRequest {

   private static ProcessEngineConfiguration cfg;

    public static void main(String[] args) {
         // https://juejin.cn/post/6844904158231789582?searchId=202311022320100CA85A719B46DC4E7751

        // Flowable工作流-高级篇
        // https://blog.csdn.net/weixin_43025151/article/details/126746124

        initProcessEngine();

       // deployment();

       // processDefinition();

      // runtimeService();

      //  managers();

       // other();

       // other2();

        history();
    }

    /**
     * 初始化流程引擎
     */
    private static void initProcessEngine(){
        //1、创建ProcessEngineConfiguration实例,该实例可以配置与调整流程引擎的设置
        cfg=new StandaloneProcessEngineConfiguration()
                //2、通常采用xml配置文件创建ProcessEngineConfiguration，这里直接采用代码的方式
                //3、配置数据库相关参数
                .setJdbcUrl("jdbc:mysql://10.201.63.153:3389/flowable_demo?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2b8&nullCatalogMeansCurrent=true")
                .setJdbcUsername("daas")
                .setJdbcPassword("daas@0987")
                .setJdbcDriver("com.mysql.jdbc.Driver")
                .setDatabaseSchemaUpdate(ProcessEngineConfiguration.DB_SCHEMA_UPDATE_TRUE);
        //4、初始化ProcessEngine流程引擎实例
        ProcessEngine processEngine=cfg.buildProcessEngine();
    }


    /**
     * 部署流程
     */
    public static void deployment() {
        //创建RepositoryService实例
        ProcessEngine processEngine= cfg.buildProcessEngine();
        RepositoryService repositoryService= processEngine.getRepositoryService();

        //加载流程
        Deployment deployment=repositoryService.createDeployment()
                .addClasspathResource("holiday-request.bpmn20.xml").deploy();
    }

    /**
     * 查询流程定义
     */
    public static void processDefinition(){
        //创建RepositoryService实例
        ProcessEngine processEngine= cfg.buildProcessEngine();
        RepositoryService repositoryService= processEngine.getRepositoryService();

        //查询流程定义
        ProcessDefinition processDefinition=repositoryService.createProcessDefinitionQuery()
                .deploymentId("1")
                .singleResult();
        System.out.println("Found process definition : "+processDefinition.getName());

    }

    public static void runtimeService(){

        //1、获取流程初始化变量
//        Scanner scanner = new Scanner(System.in);
//
//        System.out.println("Who are you?");
//        String employee = scanner.nextLine();
//
//        System.out.println("How many holidays do you want to request?");
//        Integer nrOfHolidays = Integer.valueOf(scanner.nextLine());
//
//        System.out.println("Why do you need them?");
//        String description = scanner.nextLine();
        String employee ="张三";
        Integer nrOfHolidays = Integer.valueOf("1");
        String description ="工作生活需要";

        //2、使用RuntimeService启动一个流程实例
        RuntimeService runtimeService=cfg.getRuntimeService();
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("employee", employee);
        variables.put("nrOfHolidays", nrOfHolidays);
        variables.put("description", description);
        ProcessInstance processInstance=runtimeService.startProcessInstanceByKey("holiday-request",variables);

    }

    public static void managers(){
        // //通过TaskService查询 manager 组的任务
        TaskService taskService = cfg.getTaskService();
        List<Task> tasks=taskService.createTaskQuery().taskCandidateGroup("managers").list();
        System.out.println("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            System.out.println((i+1) + ") " + tasks.get(i).getName());
        }
    }

    public static void other(){
        TaskService taskService = cfg.getTaskService();
        List<String> assignees=Arrays.asList("张三","李四");
        List<Task> tasks= taskService.createTaskQuery().taskAssigneeIds(assignees).list();
        System.out.println("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            System.out.println((i+1) + ") " + tasks.get(i).getName());
        }
    }

    public static void other2(){
        TaskService taskService = cfg.getTaskService();
        List<Task> tasks= taskService.createTaskQuery().deploymentId("1").list();
        System.out.println("You have " + tasks.size() + " tasks:");
        for (int i=0; i<tasks.size(); i++) {
            System.out.println((i+1) + ") " + tasks.get(i).getName());
        }
        //经理完成任务
        Map<String, Object> variables=new HashMap<>();
        variables = new HashMap<String, Object>();
        variables.put("approved", true);
        //任务完成，并会在离开排他网关的两条路径中，基于’approved ’流程变量选择一条
        taskService.complete("2508",variables);
    }

    public static void history(){
        //获取HistoryService实例
        HistoryService historyService=cfg.getHistoryService();
        //添加查询条件
        List<HistoricActivityInstance> activities =
                historyService.createHistoricActivityInstanceQuery()
                        //选择特定实例
                       //.processInstanceId(processInstance.getId())
                        //选择已完成的
                        .finished()
                        //根据实例完成时间升序排列
                        .orderByHistoricActivityInstanceEndTime().asc()
                        .list();

        for (HistoricActivityInstance activity : activities) {
            System.out.println(activity.getActivityId() + " tookt "
                    + activity.getDurationInMillis() + " milliseconds");
        }
    }

}

